home *** CD-ROM | disk | FTP | other *** search
/ Creative Computers / Creative Computers CD-ROM, Volume 1 (Legendary Design Technologies, Inc.)(1994).iso / text / misc / ctutor3.txt.pp / ctutor3.txt
Text File  |  1994-11-17  |  7KB  |  190 lines

  1. The Art of Deja Vu - Implementing 'for' loops in C
  2. --------------------------------------------------
  3.  
  4.       The concept of the 'loop' is one of the fundamental requirements in
  5. any language. In most advanced languages, (and 'C' is no exception) there
  6. are three types of loops, the WHILE...DO, the REPEAT...UNTIL, and the
  7. FOR...NEXT loop. The tradition basic for loop looks something like,
  8.  
  9.         10      FOR x = 0 TO 20 STEP 5
  10.         20      do some stuff...
  11.         30      NEXT x    
  12.  
  13.       The same loop in C would look like,
  14.  
  15.         int x;
  16.         for (x=0;x<=20;x=x+5) {
  17.                 do some stuff...
  18.         }
  19.  
  20.       A little fast?, lets get into some detail, a FOR...NEXT loop requires
  21. three things, an initialzer (where to start), a terminator or condition
  22. (where to end), and a step or increment (what to do after each pass of the
  23. loop). The general structure of a 'C' for loop is;
  24.  
  25.         for ( INITIALIZATION ; CONDITION or TEST ; INCREMENT ) {
  26.                 /* do stuff here */
  27.         }
  28.  
  29.         So the initialization, or 'x=1' sets the variable x to the value 0,
  30. the condition tests to see that x is less than or equal to the value 20,
  31. and the increment says to increase x by the value 5 after each pass. Notice
  32. that the basic NEXT keyword is missing?, that's because the closing brace '}'
  33. implies the next condition. Is that brace necessary? No, if you want to do
  34. just one thing, say set every fifth value of an array called Stuff[] to 0
  35. then you could use these lines,
  36.  
  37.         int Stuff[21];
  38.         int x;
  39.         for (x=0;x<=20;x=x+5) 
  40.                 Stuff[x] = 0;
  41.  
  42.         Now the closeing semicolon after the '0' implies the next statement.
  43. In fact if we wanted to clear out the entire array we could do it ALL within
  44. the brakets of the for loop, by using the post increment operator ++ as in 
  45. 'x++' which means the same as 'x = x+1' we can write out for loop like this,
  46.  
  47.         int Stuff[21];
  48.         int x;
  49.         for (x=0;x<=20;Stuff[x++]=0);
  50.  
  51.         Now the semicolon after closing braket implies the NEXT command. Here
  52. the semicolon is called the NULL operator because it is saying 'Do nothing in
  53. this loop'. Now what of our original problem, zeroing every fifth element of
  54. the array? This can also be done entirely within the brakets using the comma
  55. operator like this,
  56.  
  57.         int Stuff[21]
  58.         int x;
  59.         for (x=0;x<=20;Stuff[x]=0,x=x+5);
  60.  
  61.         The comma operator allows us to perform several operations at the
  62. same step. This can be used anywhere in a 'C' program although sometimes it
  63. is neccessary to enclose the commands in brakets, ie (Stuff[21]=0,x=x+5) in
  64. order to prevent confusion as to what the operator does. This is especialy
  65. useful in the for loop however, for instance if to variable need to be 
  66. initiallized the comma operator can be used like,
  67.  
  68.         int x,y;
  69.         for (x=0,y=20;x<20;x++);
  70.  
  71.         Now lets look at the condition, the condition in 'C' should produce
  72. some form of logical response, that is a zero value or a non-zero value. As
  73. soon as the condition evaluates to false (ie zero) the loop will end. This
  74. means that a piece of code like, 
  75.  
  76.         int x;
  77.         for (x=20;x;x--) {
  78.              printf("\n%d",x);  /* print out the value of x on a new line */
  79.         }
  80.  
  81.         Will print the numbers from 20 to 1 then quit, because when x reaches
  82. zero, the condition evaluates to false and the loop ends. Furthermore there
  83. is no rule which says you MUST include each of the three parts of the loop.
  84. This means that the example above is functionally equivalent to,
  85.  
  86.         int x;
  87.         x = 20;
  88.         for (;x;x--) printf("\n%d",x);
  89.  
  90.         In which the initializer has been left out, or even,
  91.  
  92.         int x;
  93.         for (x=20;--x;) printf("\n%d",x);
  94.  
  95.         Where the increment field has been left out. The for loop also has
  96. to features in C not found in the familiar FOR...NEXT loops of BASIC, these
  97. are the keywords 'break' and 'continue'. The format for using a 'break'
  98. command is as follows,
  99.  
  100.         for ( initializer ; condition ; increment ) {
  101.                 /* do stuff ... */
  102.                 if ( condition2 ) break;
  103.                 /* do other stuff ... */
  104.         }
  105.         /* do stuff outside loop */
  106.  
  107.         What the break command does is force the for loop to end, right then
  108. and there. So in the above general format if the program evaluates
  109.  'condition2' to be true (ie non-zero) then the break instruction is executed
  110. causing execution of the program to skip to the 'stuff outside loop' without
  111. executing the 'other stuff'. The 'continue' command works slightly
  112. differently, it's format is,
  113.  
  114.         for ( initializer ; condition ; increment ) {
  115.                 /* do stuff ... */
  116.                 if ( condition2 ) continue;
  117.                 /* do other stuff ... */
  118.         }
  119.  
  120.         The way this command works is to force the loop to go to the NEXT
  121. command that is if condition2 evaluates true, the continue command will force
  122. the loop to perform the increment and condition steps of the loop as if it
  123. had reached the end of the loop, but without ever executing the 'do other
  124. stuff' portion of the code. An analogy in BASIC would be,
  125.  
  126.         10  FOR x = 1 to 10
  127.         20  rem -- do stuff --
  128.         30  if condition2 goto 50:  rem -- this is the 'continue'
  129.         40  rem -- do other stuff --
  130.         50  NEXT x
  131.  
  132.         The rest of this tutorial is made up of some code fragments showing
  133. uses of 'C' for loops.
  134.  
  135. /******************************************
  136.    convert long int to zero padded ascii, 
  137.    the value in num is NOT preserved      
  138. *******************************************/
  139. #define MAX_DIGITS 9
  140.  
  141. long num;
  142. int x;
  143. char *string = "        "; /* string is MAX_DIGITS long */
  144.  
  145.      for ( x=MAX_DIGITS ; num/=10 ; *(string+x--)= num%10+'0');
  146.  
  147. /* end of conversion */
  148.  
  149. /***********************************************
  150.   count the number of records in a linked list
  151. ************************************************/
  152.  
  153. /* note: "node->next" indicates next node in list */
  154.  
  155. struct node *root; /* pointer to first node in list */
  156. struct node *work; /* temp pointer */
  157. int records;
  158.  
  159.         for ( work=root,records=0 ; work ; records++,work=work->next );
  160.  
  161. /* end of count, records now contains # of elements, work is NULL (ie 0) */
  162.  
  163. /***********************************************
  164.   find a matching password in a list 
  165. ***********************************************/
  166.  
  167. /* notes: "node->next" indicates next element in list,
  168.           "node->pswd" is a pointer to a string of characters */
  169.  
  170. struct node *root,*work;
  171. char *pswd; /* assumed to already point to the input password */
  172.  
  173.     for (work=root; work; ) {
  174.              if (strcmp(pswd,work->pswd)==0) break;
  175.              work = work->next;
  176.         }
  177.  
  178. /* work now points to the matching node for the supplied password, or
  179.    work will now equal NULL if the password was not found
  180. */
  181.  
  182.         Thus concludes our attempts at chasing ourselves in 'C' using the
  183. for loop. Any questions? You can direct them at me Stephen Orr on this board
  184. until about Sept. 9 after which I'll be out of town for 4 months!
  185.  
  186.         I hope it's been useful! Bye for now.
  187.  
  188.                    Stephen Orr
  189.  
  190.